<template>
    <div>
        <el-dialog :title="title" :visible="visible" width="1000px" :before-close="close" :destroy-on-close="true" :close-on-click-modal="false">
            <el-form :model="ruleForm" :rules="rules" ref="formRef" label-width="120px" class="demo-ruleForm">
                <el-row :gutter="26">
                    <!-- 左列 -->
                    <el-col :span="12">
                        <el-form-item label="名称" prop='name'>
                            <el-input v-model="ruleForm.name" placeholder="请输入名称"></el-input>
                        </el-form-item>
                        <el-form-item label="简称" prop='short_name'>
                            <el-input v-model="ruleForm.short_name" placeholder="请输入简称"></el-input>
                        </el-form-item>

                        <el-form-item label="logo" prop="logo">
                            <Upload v-model="ruleForm.logo" />
                        </el-form-item>

                        <el-form-item label="地址" prop="address">
                            <el-input v-model="ruleForm.address" placeholder="请输入地址"></el-input>
                        </el-form-item>

                        <el-form-item label="配送范围" prop="range">
                            <el-button type="primary"
                                :disable="Array.isArray(ruleForm.address) && ruleForm.address.length > 0"
                                @click="fwSelect">{{Array.isArray(defaultRange)?'修改':'选择'}}配送范围</el-button>
                        </el-form-item>

                        <el-form-item label="营业执照" prop="business_license">
                            <Upload v-model="ruleForm.business_license" />
                        </el-form-item>

                        <el-form-item label="绑定打印机" prop="printer_id" v-if="user.identity == 1">
                            <el-select v-model="ruleForm.printer_id" placeholder="请选择打印机">
                                <el-option v-for="i in printerList" :key="i.id" :label="i.label" :value="i.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="支付配置" prop="pay_config_id" v-if="user.identity == 1">
                            <el-select v-model="ruleForm.pay_config_id" placeholder="请选择支付配置">
                                <el-option v-for="i in payList" :label="i.label" :value="i.value" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="排序" prop="sort" v-if="user.identity == 1">
                            <el-input type="number" v-model="ruleForm.sort" placeholder="请输入排序"></el-input>
                        </el-form-item>

                        <el-form-item label="推荐商品数量" prop="recommend_limit" v-if="user.identity == 1">
                            <el-input type="number" v-model="ruleForm.recommend_limit"
                                placeholder="请输入推荐商品数量"></el-input>
                        </el-form-item>
                        <el-form-item label="是否桶装水商家" prop="is_water_merchant" v-if="user.identity == 1">
                            <el-switch v-model="ruleForm.is_water_merchant" :active-value="1" :inactive-value="0"
                                active-text="是" inactive-text="否"></el-switch>
                        </el-form-item>

                        <el-form-item label="商户公告" prop="announcement">
                            <el-input v-model="ruleForm.announcement" placeholder="请输入商户公告"></el-input>
                        </el-form-item>
                        <!-- //is_water_merchant -->

                    </el-col>

                    <!-- 右列 -->
                    <el-col :span="12">
                        <el-form-item label="营业状态" prop="status">
                            <el-select v-model="ruleForm.status" placeholder="请选择">
                                <el-option label="营业中" :value="1" />
                                <el-option label="休息中" :value="0" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="营业时间" prop="date">
                            <el-time-picker is-range format="HH:mm" value-format="HH:mm" v-model="ruleForm.date"
                                range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                                placeholder="选择时间范围">
                            </el-time-picker>
                        </el-form-item>

                        <el-form-item label="商户描述" prop="description">
                            <el-input type="text" v-model="ruleForm.description" placeholder="请输入商户描述" />
                        </el-form-item>

                        <el-form-item label="联系人姓名" prop="contact_name">
                            <el-input type="text" v-model="ruleForm.contact_name" placeholder="请输入联系人姓名" />
                        </el-form-item>

                        <el-form-item label="联系人电话" prop="contact_phone">
                            <el-input type="tel" :maxlength="11" v-model="ruleForm.contact_phone"
                                placeholder="请输入联系人电话" />
                        </el-form-item>

                        <el-form-item label="营业执照号码" prop="business_license_number">
                            <el-input v-model="ruleForm.business_license_number"
                                placeholder="请输入营业执照号码" />
                        </el-form-item>

                        <el-form-item label="店铺分类" prop="category_ids">
                            <el-select v-model="ruleForm.category_ids" placeholder="请选择" multiple>
                                <el-option :value="i.value" :label="i.label" v-for="i in categoryList" />
                            </el-select>
                        </el-form-item>

                        <el-form-item label="满多少免配送费" prop="free_delivery_amount">
                            <el-input-number type="number" v-model="ruleForm.free_delivery_amount"
                                placeholder="请输入金额" />
                        </el-form-item>

                        <!-- 新增配送方式选项 -->
                        <el-form-item label="是否配送到小区" prop="show_community_delivery">
                            <el-switch v-model="ruleForm.show_community_delivery" :active-value="1" :inactive-value="0"
                                active-text="是" inactive-text="否"></el-switch>
                        </el-form-item>

                        <el-form-item label="配送到小区价格" prop="community_delivery_fee"
                            v-if="ruleForm.show_community_delivery">
                            <el-input-number type="number" style="width: 100%;"
                                v-model="ruleForm.community_delivery_fee" :min="0" placeholder="请输入配送到小区价格">
                                <template slot="append">元</template>
                            </el-input-number>
                        </el-form-item>

                        <el-form-item label="是否送货上门" prop="show_home_delivery">
                            <el-switch v-model="ruleForm.show_home_delivery" active-text="是" :active-value="1"
                                :inactive-value="0" inactive-text="否"></el-switch>
                        </el-form-item>

                        <el-form-item label="送货上门价格" prop="home_delivery_fee" v-if="ruleForm.show_home_delivery">
                            <el-input-number type="number" style="width: 100%;" v-model="ruleForm.home_delivery_fee"
                                :min="0" placeholder="请输入送货上门价格">
                                <template slot="append">元</template>
                            </el-input-number>
                        </el-form-item>




                        <el-form-item label="是否次日达" prop="show_next_day_delivery">
                            <el-switch v-model="ruleForm.show_next_day_delivery" active-text="是" :active-value="1"
                                :inactive-value="0" inactive-text="否"></el-switch>
                        </el-form-item>

                        <el-form-item label="是否闪送" prop="show_flash_delivery">
                            <el-switch v-model="ruleForm.show_flash_delivery" active-text="是" :active-value="1"
                                :inactive-value="0" inactive-text="否"></el-switch>
                        </el-form-item>


                        <el-form-item label="是否支持自提" prop="show_self_pickup">
                            <el-switch v-model="ruleForm.show_self_pickup" active-text="是" inactive-text="否"
                                :active-value="1" :inactive-value="0"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
            </span>
        </el-dialog>
        <!-- <el-dialog title="地址选择" :visible="mapVisible">
            <MapPointPicker ref="MapPointRef" @point-selected="handlePointSelected" />
            <span slot="footer" class="dialog-footer">
                <el-button @click="mapVisible = false">取 消</el-button>
                <el-button type="primary" @click="mapSubmit" :loading="loading">确 定</el-button>
            </span>
        </el-dialog> -->
        <div v-if="showMapSelector">
            <el-dialog title="配送范围" width="70vw" :show-close="true"  :visible="showMapSelector"
                :destroy-on-close="true">
                <MapRangeSelector :init-center="ruleForm.address" :init-zoom="11"
                    @circle-selected="handleCircleSelected" @polygon-selected="handlePolygonSelected" :center="pint"
                    :range="defaultRange" ref="MapRangeSelectorRef" />
                <span slot="footer" class="dialog-footer">
                    <el-button @click="closeMap">取 消</el-button>
                    <el-button type="primary" @click="fwSubmit">确 定</el-button>
                </span>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { merchantAdd, merchantEdit } from '../api/index';
import Upload from '@/components/Upload.vue';
import MapRangeSelector from './MapRangeSelector.vue';
// import MapPointPicker from './MapPointPicker.vue';
import { Message } from 'element-ui';
import axios from 'axios';
export default {
    props: ['applet_id', 'categoryList', 'printerList', 'payList'],
    data() {
        const user = JSON.parse(localStorage.getItem('user'));
        const validateCommunityFee = (rule, value, callback) => {
            if (this.ruleForm.show_community_delivery === 1 && (value === null || value === '' || value === undefined)) {
                callback(new Error('请输入配送到小区配送费'));
            } else {
                callback();
            }
        };
        const validateHomeFee = (rule, value, callback) => {
            if (this.ruleForm.show_community_delivery === 1 && (value === null || value === '' || value === undefined)) {
                callback(new Error('请输入送货上门配送费'));
            } else {
                callback();
            }
        };
        return {
            user: user,
            showMapSelector: false,
            mapVisible: false,
            isEdit: false,
            options: [],
            title: '',
            visible: false,
            loading: false,
            selectedArea: null,
            pint: [],
            defaultRange: [],
            defaultAddr: '',
            ruleForm: {
                name: null,
                short_name: null,
                logo: null,
                address: null,
                business_license: null,
                business_license_number: null,
                status: null,
                description: null,
                contact_name: null,
                printer_id: null,
                pay_config_id: null,
                recommend_limit: 0,
                is_water_merchant: 0,
                sort: null,
                announcement: null,
                home_delivery_fee:null,
                free_delivery_amount:null,
                community_delivery_fee:null,
                date: [],
                free_delivery_amount:0,
                home_delivery_fee: 0,
                community_delivery_fee: 0,
                contact_phone: null,
                // delivery_range: null,
                category_ids: [],
                show_home_delivery: 0,
                show_community_delivery: 0,
                show_next_day_delivery: 0,
                show_flash_delivery: 0,
                show_self_pickup: 0,
                range: []
                // longitude: null,
                // latitude: null,
            },
            rules: {
                name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                ],
                // short_name: [
                //     { required: true, message: '请输入简称', trigger: 'blur' },
                //     { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
                // ],
                logo: [
                    { required: true, message: '请上传logo', trigger: 'blur' }
                ],
                address: [
                    { required: true, message: '请输入地址', trigger: 'blur' }
                ],
                business_license: [
                    { required: true, message: '请上传营业执照', trigger: 'blur' }
                ],
                business_license_number: [
                    { required: true, message: '请输入营业执照号', trigger: 'blur' }
                ],
                status: [
                    { required: true, message: '请选择营业状态', trigger: 'blur' }
                ],
                // description: [
                //     { required: true, message: '请输入商户描述', trigger: 'blur' }
                // ],
                contact_name: [
                    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
                ],
                contact_phone: [
                    { required: true, message: '请输入联系人电话', trigger: 'blur' }
                ],
                // printer_id: [
                //     { required: user.identity == 1, message: '请选择打印机', trigger: 'blur' }
                // ],
                // pay_config_id: [
                //     { required: user.identity == 1, message: '请选择支付配置', trigger: 'blur' }
                // ],
                // recommend_limit: [
                //     { required: user.identity == 1, message: '请输入首页推荐商品数量', trigger: 'blur' }
                // ],
                // category_ids: [
                //     { required: true, message: '请选择店铺分类', trigger: 'blur' }
                // ],
                // sort: [
                //     { required: user.identity == 1, message: '请输入排序', trigger: 'blur' }
                // ],
                // announcement: [
                //     { required: true, message: '请输入公告', trigger: 'blur' }
                // ],
                date: [
                    { required: true, message: '请选择营业时间', trigger: 'blur' }
                ],
                community_delivery_fee: [
                    { validator: validateCommunityFee, trigger: 'blur' }
                ],
                home_delivery_fee: [
                    { validator: validateHomeFee, trigger: 'blur' }
                ],
                range: [
                    { required: true, message: '请选择配送范围', trigger: 'blur' }
                ],
            },
        }
    },
    components: { Upload, MapRangeSelector }, //MapRangeSelector, MapPointPicker 
    created() {

    },
    methods: {
        add() {
            this.visible = true;
            this.isEdit = false;
            this.title = '新增商户';
            let temp = {};
            Object.keys(this.ruleForm).forEach(key => {
                temp[key] = this.ruleForm[key]
            })
            this.ruleForm = temp;
        },
        edit(data) {
            this.title = '修改商户';
            this.visible = true;
            this.isEdit = true;
            this.editId = data.id;
            this.defaultAddr = data.address;
            this.defaultRange = data.range ? JSON.parse(data.range) : null;
            this.pint = [Number(data.longitude), Number(data.latitude)];
            console.log(data);
            
            Object.keys(this.ruleForm).forEach(key => {
                if (key.includes('_fee') || key.includes('_amount')) {
                    console.log('key',key);
                    
                    this.ruleForm[key] = data[key]
                } else {
                    this.ruleForm[key] = data[key]
                }

            })
            console.log('ruleform' + this.ruleForm);

        },
        close() {
            this.$refs.formRef.resetFields();
            this.visible = false;

        },
        mapClose() {
            this.mapVisible = false;
        },
        handlePointSelected(point) {
            this.ruleForm.address = point;
        },
        mapSubmit() {
            if (!Array.isArray(this.ruleForm.address) || this.ruleForm.address.length == 0) {
                Message.error('请选择地址')
                return
            }
            this.mapVisible = false;

        },
        fwSelect() {
            if (!this.ruleForm.address) {
                Message.error('请输入地址')
                return
            }
            if (this.defaultAddr === this.ruleForm.address) {

                console.log('pint==>', this.pint);
                console.log('range==>', this.defaultRange);

                this.showMapSelector = true;
                return
            }
            axios.get('https://restapi.amap.com/v3/geocode/geo', {
                params: {
                    key: '559fcb3a8fc70c9be5201519b1eebd0d',
                    address: this.ruleForm.address,
                    city: '成都'
                }
            }).then(response => {
                if (response.data.status === '1' && response.data.geocodes.length > 0) {
                    const location = response.data.geocodes[0].location
                    const [lng, lat] = location.split(',')
                    console.log('经度:', lng, '纬度:', lat)
                    this.pint = [lng, lat];
                    this.showMapSelector = true;
                } else {
                    Message.error('输入地址不正确');
                    console.error('地理编码失败:', response.data)
                }
            }).catch(error => {
                console.error('请求失败:', error)
            })
        },
        closeMap() {
            this.$refs.MapRangeSelectorRef.clearPolygonSelection();
            this.showMapSelector = false;
        },
        fwSubmit() {
            const fw = this.$refs.MapRangeSelectorRef.endEditing()
            console.log(fw);
            this.$refs.MapRangeSelectorRef.clearPolygonSelection();
            this.showMapSelector = false;

            this.ruleForm.range = fw;



        },
        submit() {
            this.$refs.formRef.validate(async (res) => {
                if (res) {
                    this.loading = true;
                    try {
                        let p = this.ruleForm
                        p.business_start_time = this.ruleForm.date[0];
                        p.business_end_time = this.ruleForm.date[1];
                        p.applet_id = this.applet_id
                        let res = this.isEdit ? await merchantEdit({ ...p, id: this.editId }) : await merchantAdd(p);
                        this.loading = false;
                        this.$refs.formRef.resetFields();
                        const msg = this.title + '成功';
                        this.$message({
                            type: 'success',
                            message: msg
                        })
                        this.close();
                        this.$emit('refresh', 1);
                    } catch (err) {
                        console.log(err);

                        this.loading = false;
                    }
                }
            })
        },
        mapSelect() {
            this.mapVisible = true;
        },

        handleCircleSelected(area) {
            this.selectedArea = {
                type: 'circle',
                ...area
            }
            this.$message.success('圆形范围选择完成')
        },
        handlePolygonSelected(area) {
            this.selectedArea = {
                type: 'polygon',
                ...area
            }
            this.$message.success('多边形范围选择完成')
        }
        // getAddr(){
        //     window.open('https://www.lddgo.net/convert/position')
        // }
    },
}
</script>

<style lang='scss' scoped>
.custom-dialog{
    height: 60vh;
}
.avatar-uploader .el-upload {
    border: 1px dashed red;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>